import {
  getNewCartGoods,
  mergeCart,
  findCart,
  insertCart,
  deleteCart,
  updateCart,
  checkAllCart
} from '@/api/cart'

// 购物车状态
export default {
  namespaced: true,
  state: {
    // 购物车列表
    list: []
  },

  mutations: {
    // 修改购物车
    setCartList (state, data) {
      state.list = data
    },
    // 添加
    addCart (state, data) {
      // 有，增加数量
      // 没有，追加到最前面
      const index = state.list.findIndex(item => item.skuId === data.skuId)
      if (index >= 0) {
        state.list[index].count += data.count
      } else {
        state.list.unshift(data)
      }
    },
    // 删除
    delCart (state, skuId) {
      const index = state.list.findIndex(item => item.skuId === skuId)
      state.list.splice(index, 1)
    },
    // 更新
    updateCart (state, goods) {
      const obj = state.list.find(item => item.skuId === goods.skuId)
      for (const key in goods) {
        if (goods[key] !== null) {
          obj[key] = goods[key]
        }
      }
    }
  },

  actions: {
    // 进入页面就获取最新商品信息
    getNewGoodsList (store) {
      return new Promise((resolve) => {
        if (store.rootState.user.profile.token) {
          // 已登录
          findCart().then((res) => {
            store.commit('setCartList', res.result)
          })
          resolve()
        } else {
          // 未登录
          // 遍历购物车列表
          store.state.list.map(item => {
            getNewCartGoods(item.skuId).then(res => {
              store.commit('updateCart', { skuId: item.skuId, ...res.result })
            })
          })
          resolve()
        }
      })
    },
    // 增加
    addCart (store, data) {
      return new Promise((resolve) => {
        if (store.rootState.user.profile.token) {
          // 已登录
          insertCart({ skuId: data.skuId, count: data.count }).then(() => {
            store.dispatch('getNewGoodsList')
            resolve('加入购物车成功--服务器')
          })
        } else {
          // 未登录
          console.log(data)
          store.commit('addCart', data)
          resolve('加入购物车成功')
        }
      })
    },
    // 删除
    delCart (store, skuId) {
      return new Promise((resolve) => {
        if (store.rootState.user.profile.token) {
          // 已登录
          deleteCart([skuId]).then(() => {
            store.dispatch('getNewGoodsList')
            resolve('删除成功---服务器')
          })
        } else {
          // 未登录
          store.commit('delCart', skuId)
          resolve('删除成功')
        }
      })
    },
    // 更新
    updateCart (store, goods) {
      return new Promise((resolve) => {
        if (store.rootState.user.profile.token) {
          // 已登录
          updateCart({ skuId: goods.skuId, selected: goods.selected, count: goods.count }).then((res) => {
            store.dispatch('getNewGoodsList')
            resolve()
          })
          resolve()
        } else {
          // 未登录
          store.commit('updateCart', goods)
          resolve('更新成功')
        }
      })
    },
    // 全选
    checkAllCart (store, selected) {
      return new Promise((resolve) => {
        if (store.rootState.user.profile.token) {
          // 已登录
          const skuIds = store.getters.validList.map(item => item.skuId)
          checkAllCart({ selected: selected, ids: skuIds }).then(() => {
            store.dispatch('getNewGoodsList')
          })
          resolve()
        } else {
          // 未登录
          store.getters.validList.forEach((item) => {
            item.selected = selected
            store.commit('updateCart', selected)
          })
          resolve()
        }
      })
    },
    // 批量删除
    batchDeleteCart (store, isInvaild) {
      return new Promise((resolve) => {
        if (store.rootState.user.profile.token) {
          // 已登录
          const skuIds = store.getters[isInvaild === true ? 'invalidList' : 'selectedList'].map(item => item.skuId)
          deleteCart(skuIds).then(() => {
            store.dispatch('getNewGoodsList')
            resolve('删除成功---服务器')
          })
          resolve()
        } else {
          // 未登录
          store.getters[isInvaild === true ? 'invalidList' : 'selectedList'].forEach(item => {
            store.commit('delCart', item.skuId)
          })
          resolve('删除成功')
        }
      })
    },
    // 购物车页面修改规格
    updateCartGoodsSku (store, { oldSkuId, newSkuObj }) {
      return new Promise((resolve) => {
        if (store.rootState.user.profile.token) {
          // 已登录
          // 获取到旧值
          const oldVal = store.state.list.find(item => item.skuId === oldSkuId)
          // 删除旧值
          deleteCart([oldVal.skuId]).then(() => {
            store.dispatch('getNewGoodsList')
            resolve('删除成功---服务器')
          })
          // 合并旧值和新值
          const newVal = { ...oldVal, ...newSkuObj, stock: newSkuObj.inventory }
          // 添加
          insertCart({ skuId: newVal.skuId, count: newVal.count }).then(() => {
            store.dispatch('getNewGoodsList')
            resolve('加入购物车成功--服务器')
          })
          resolve()
        } else {
          // 未登录
          console.log(1)
          // 获取到旧值
          const oldVal = store.state.list.find(item => item.skuId === oldSkuId)
          // 删除旧值
          store.commit('delCart', oldSkuId)
          // 合并旧值和新值
          const newVal = { ...oldVal, ...newSkuObj, stock: newSkuObj.inventory }
          // 添加
          store.commit('addCart', newVal)
          resolve()
        }
      })
    },
    // 合并购物车
    async mergeLocalCart (store) {
      // 获取参数
      const cartParams = store.getters.validList.map(item => {
        return {
          skuId: item.skuId,
          selected: item.selected,
          count: item.count
        }
      })
      // 发请求
      await mergeCart(cartParams)
      // 清空本地购物车数据
      store.commit('setCartList', [])
    }
  },

  getters: {
    // 有效商品列表
    validList (state) {
      return state.list.filter(item => item.isEffective && item.stock > 0)
    },
    // 有效商品件数
    validTotal (state, getters) {
      let sum = 0
      getters.validList.forEach(element => {
        sum += element.count
      })
      return sum
    },
    // 有效商品总金额
    validAmount (state, getters) {
      return getters.validList.reduce((count, item) => {
        return count + item.price * item.count * 100
      }, 0) / 100
    },
    // 无效商品列表
    invalidList (state) {
      return state.list.filter(item => !item.isEffective && item.stock === 0)
    },
    // 选中商品列表
    selectedList (state, getters) {
      return getters.validList.filter(item => item.selected)
    },
    // 选中商品件数
    selectedTotal (state, getters) {
      let sum = 0
      getters.selectedList.forEach(element => {
        sum += element.count
      })
      return sum
    },
    // 选中商品总金额
    selectedAmount (state, getters) {
      return getters.selectedList.reduce((count, item) => {
        return count + item.price * item.count * 100
      }, 0) / 100
    },
    // 是否全选
    isCheckAll (state, getters) {
      return getters.validList.length === getters.selectedList.length && getters.validList.length !== 0
    }
  }
}
